package com.csust.senior.dao;

import com.csust.senior.utils.JDBCUtilsV2;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


/*
*
*将共性的数据库操作封装在BaseDAO里
*
* */
public class BaseDAO {
    /*
    * 通用的增删改的方法
    * @param sql  要执行的sql语句
    * @param params sql语句中的占位符
    * @return 受影响的行数
    * */

    public int executeUpdate (String sql ,Object... params) throws SQLException {
        //1.创建PreparedStatement对象，对sql预编译
        Connection conn = JDBCUtilsV2.getConnection();
        //2.
        PreparedStatement ps = conn.prepareStatement(sql);
        //3.
        if (params !=null && params.length >0) {
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
        }
        //4.
        int row = ps.executeUpdate();
        ps.close();
        if(conn.getAutoCommit()){
            JDBCUtilsV2.release();
        }
        return row;
        //5.

    }


    public <T> List<T> executeQuery (String sql, Class<T> clazz, Object... params) throws Exception {
        Connection conn = JDBCUtilsV2.getConnection();

        PreparedStatement ps = conn.prepareStatement(sql);

        if (params !=null && params.length >0) {
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
        }
        ResultSet rs = ps.executeQuery();

        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount();
        List<T> list = new ArrayList<T>();
        while (rs.next()) {
            T t = clazz.newInstance();

            for (int i = 1; i <= columnCount; i++) {
                Object value = rs.getObject(i);
                String columnName = md.getColumnLabel(i);
                Field field = clazz.getDeclaredField(columnName);
                field.setAccessible(true);
                field.set(t, value);

            }
            list.add(t);
        }
        rs.close();
        ps.close();
        if(conn.getAutoCommit()){
            JDBCUtilsV2.release();
        }
        return list;
    }

    public <T> T executeQueryBean (String sql, Class<T> clazz, Object... params) throws Exception {
        List<T> list = this.executeQuery(sql, clazz, params);
        if (list== null && list.size() == 0) {
            return null;

        }

        return list.get(0);
    }
}
